package com.hoshiicloud.withdraw.util.gongmao;

import cn.hutool.crypto.digest.DigestUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;


/**
 * 工猫签名工具
 */
@Configuration
public class SignUtil {

	public static String APPKEY;

	public static String APPSECRET;

	public static final String NONCE = "nonce";
	public static final String TIMESTAMP = "timestamp";
	public static final String SIGN = "sign";


	public static String getAPPKEY() {
		return APPKEY;
	}

	@Value("${gongmao.appKey}")
	public void setAPPKEY(String APPKEY) {
		SignUtil.APPKEY = APPKEY;
	}

	public static String getAPPSECRET() {
		return APPSECRET;
	}

	@Value("${gongmao.appSecret}")
	public void setAPPSECRET(String APPSECRET) {
		SignUtil.APPSECRET = APPSECRET;
	}

	/**
	 * 获取签名
	 *
	 * @param paramMap  包含所有业务参数，和appKey,nonce,timestamp这3个公共参数
	 * @param appSecret
	 * @return
	 */
	public static String getSign(Map<String, Object> paramMap, String appSecret) {
		String text = getUrlText(paramMap);
		text += "&appSecret=" + appSecret;
		return DigestUtil.md5Hex(text).toUpperCase();
	}

	private static String getUrlText(Map<String, Object> beanMap) {
		beanMap = getSortedMap(beanMap);
		StringBuilder builder = new StringBuilder();
		for (String key : beanMap.keySet()) {
			String value = beanMap.get(key).toString();
			builder.append(key);
			builder.append('=');
			builder.append(value);
			builder.append('&');
		}
		String text = builder.toString();
		return text.substring(0, text.length() - 1);
	}

	/**
	 * 对普通map进行排序
	 *
	 * @param paramMap
	 * @return
	 */
	private static Map<String, Object> getSortedMap(Map<String, Object> paramMap) {
		SortedMap<String, Object> map = new TreeMap<>();
		for (String key : paramMap.keySet()) {
			if (key != null && !APPSECRET.equals(key)) {
				Object value = paramMap.get(key);
				if (value != null) {
					String valueStr = String.valueOf(value);
					if (valueStr != null && !"".equals(valueStr)) {
						map.put(key, value);
					}
				}
			}
		}
		return map;
	}
}
